﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace TwitterChat
{
    public class TwitterService : ITwitterService
    {
        public IEnumerable<ChanelDTO> GetAllChanels()
        {
            TwitterChatEntities context = new TwitterChatEntities();
            var chanels = context.Chanels.OrderBy(c => c.ChanelName).ToList();

            IEnumerable<ChanelDTO> chanelsDTOs = chanels.Select(c => ChanelDTO.CreateFromChanel(c));
            return chanelsDTOs;
        }

        public IEnumerable<MessageDTO> GetMessages(MessagesContactor contractor) 
        {
            TwitterChatEntities context = new TwitterChatEntities();
            List<MessageDTO> result = new List<MessageDTO>();

            int counter = 0;
            foreach (var message in context.Messages) 
            {
                if (message.ChanelId == contractor.ChannelId && counter <= contractor.NumberOfMessagesToBeShown) 
                {
                    result.Add(MessageDTO.CreateFromMessage(message));
                    if (counter == contractor.NumberOfMessagesToBeShown) 
                    {
                        break;
                    }
                }
            }
            return result;
        }

        public void CreateChanel(ChanelDTO chanelToReset) 
        {
            TwitterChatEntities context = new TwitterChatEntities();

            if (context.Chanels.Count(ch => ch.ChanelName == chanelToReset.ChanelName) > 0)
            {
                string query = string.Format("Delete from Messages Where ChanelId = {0}", chanelToReset.ChanelId);
                context.ExecuteStoreQuery<object>(query);
                context.SaveChanges();
            }
            else 
            {
                Chanel newChanel = chanelToReset.ConvertToChannel();
                context.Chanels.AddObject(newChanel);
                context.SaveChanges();
            }
        }

        public void PostMessage(MessageDTO message) 
        {
            TwitterChatEntities context = new TwitterChatEntities();
            Message messageToAdd = message.ToMessage();
            context.Messages.AddObject(messageToAdd);
            context.SaveChanges();
        }
    }
}
